package com.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电话号码的字母组合
 * 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
 *
 * @author winson
 * @create 2022-03-29 11:40
 */
public class LetterCombinationsSolution {

    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits.length() == 0) {
            return res;
        }
        Map<Character, String> numLetterMap = new HashMap<>();
        numLetterMap.put('2', "abc");
        numLetterMap.put('3', "def");
        numLetterMap.put('4', "ghi");
        numLetterMap.put('5', "jkl");
        numLetterMap.put('6', "mno");
        numLetterMap.put('7', "pqrs");
        numLetterMap.put('8', "tuv");
        numLetterMap.put('9', "wxyz");
        backtrack(res, numLetterMap, digits, 0, new StringBuffer());
        return res;
    }

    private void backtrack(List<String> res, Map<Character, String> numLetterMap, String digits, int i, StringBuffer stringBuffer) {
        if (digits.length() == i) {
            res.add(stringBuffer.toString());
        } else {
            Character d = digits.charAt(i);
            // 获取对应的字母
            String letter = numLetterMap.get(d);
            // 开始处理字母
            for (int j = 0; j < letter.length(); j++) {
                stringBuffer.append(letter.charAt(j));
                backtrack(res, numLetterMap, digits, i + 1, stringBuffer);
                stringBuffer.deleteCharAt(i);
            }
        }
    }
}
